package Servelt;

import DatabaseAccessing.ProductModelController;
import DatabaseAccessing.Products;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayAllProducts extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        ProductModelController controller = new ProductModelController();

        if (request.getParameter("action") != null
                && request.getParameter("action").equals("del")) {
            String idStr = request.getParameter("ID");
            if (idStr != null) {
                try {
                    int id = Integer.parseInt(idStr);
                    controller.deleteProduct(id);

                } catch (NumberFormatException exp) {
                    System.err.println("Error(processRequest) NumberFormatError"
                            + exp.getMessage());
                }
            }
        }
        
        List<Products> products = controller.viewAllProducts();
        RequestDispatcher rd = request.getRequestDispatcher("AdminEditProducts.jsp");
        request.setAttribute("allProducts", products);
        rd.forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    public String getServletInfo() {
        return "Contacts the DB Controller and calls the AdminEditProducts page";
    }
}
